<?php

namespace App\Command\ExportFile;

use App\Service;
use EchoPHP\Console\Command;
use EchoPHP\Facades\Db as Db;
use EchoPHP\Facades\Log as Log;
use App\Web\Model\CaseModel;
use App\Web\Model\CaseResume as CaseResumeModel;

class ExportToDocx extends Command {
    // php /www/RPO-pro/Command ExportFile:ExportToDocx
    protected $signature = "ExportFile:ExportToDocx";
    protected $description = '导出简历';

    protected $helper;
    protected $configPath = ROOT_PATH . '/app/Command/ExportFile/position.txt';
    protected $pos;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct() {
        parent::__construct();
    }

    /*
     * 生成过程
     */
    public function handle() {
        $this->pos = $this->getConfig($this->configPath, true);
        $this->helper = new DocxExportHelper($this->configPath, $this->pos);
        $beginTime = time();
        $runFlag = true;
        //while ($runFlag && time() - $beginTime < 1 * 60) {
        while ($runFlag && time() - $beginTime < (20 * 60 - 10)) {
            try {
                $sql = "select id, templateid, creator, extraparams from ResumeExport where id>=? and status='01' and createdate < SUBTIME(NOW(),'0:0:2') order by id asc";
                $taskList = Db::select($sql, [$this->pos['id'] - 1000], 0, 10);
                if (count($taskList) == 0) {
                    $this->writeLog(['title' => '没有待导出任务', 'latesttaskid' => $this->pos['id']], false);
                    sleep(5);
                    continue;
                }
                foreach ($taskList as $task) {
                    //保证并发时，一个导出任务只能被一个后台程序执行。
                    $result = $this->helper->openTask($task['id']);
                    if ($result !== 1) {
                        continue;
                    }

                    if (empty($task['extraparams'])) {
                        $this->helper->finishTask($task['id'], 0);
                        continue;
                    }

                    $extraparams = unserialize($task['extraparams']);
                    if (!@is_array($extraparams)) {
                        $this->helper->finishTask($task['id'], 0);
                        continue;
                    }

                    $result = $this->helper->export($task['id'], $task['templateid'], $extraparams, $task['creator']);
                    $this->writeLog(['title' => '导出完毕', 'taskid' => $task['id'], 'processedcount' => $result['resumecount'], 'relativepathname' => $result['relativepathname']], false);
                }
            } catch (\Exception $e) {
                $info = ['pos' => $this->pos];
                if (!empty($task)) {
                    $info['task'] = $task;
                } elseif (!empty($taskList)) {
                    $info['taskList'] = array_map(function ($task) {
                        return !empty($task['id']) ? $task['id'] : '';
                    }, $taskList);
                }
                Log::error(e_dump($e), $info, 'cmd');
                sleep(10);
            }
        }
    }

    protected function getConfig($path, $autoInit = false, $default = ['id' => 0]) {
        //配置文件的读取
        if (!file_exists($path)) {
            $this->writeLog(['title' => '配置文件不存在', 'path' => $path]);
            if (!$autoInit) exit;
            $this->writeLog(['title' => '自动初始化配置文件', 'data' => $default]);
            file_put_contents($path, json_encode($default));
        }
        $fileContent = @file_get_contents($path);
        $config = @json_decode($fileContent, TRUE);
        if (empty($config)) {
            $this->writeLog(['title' => '配置文件格式异常', 'data' => $fileContent]);
            if (!$autoInit) exit;
            $this->writeLog(['title' => '自动初始化配置文件', 'data' => $default]);
            file_put_contents($path, json_encode($default));
            return $default;
        }
        return $this->readConfig($config, $default);
    }

    //将source中键值并入以template格式为基准的结构中
    function readConfig(&$source, &$template) {
        if (!is_array($source)) return $template;
        foreach ($template as $k => $v) {
            if (is_array($v)) {
                $this->readConfig($source[$k], $template[$k]);
            } elseif (isset($source[$k])) {
                //仅当配置文件内数值比默认值大，采用配置文件内容，否则使用默认值。
                if ($source[$k] >= $template[$k]) {
                    $template[$k] = $source[$k];
                }
            }
        }
        return $template;
    }

    function writeLog($logInfo, $toLogFile = true) {
        /*
        $context['title'] = 'description';
        $context['key'] = $value;
        */
        $title = $logInfo['title'];
        unset ($logInfo['title']);
        $this->output->writeln(PHP_EOL . "********************************************************************************");
        $this->output->writeln(var_export($logInfo, true) . PHP_EOL);
        $this->output->writeln($this->description . '->' . $title . " 系统时间：" . date("Y-m-d H:i:s"));
        $this->output->writeln("********************************************************************************" . PHP_EOL);
        if ($toLogFile) Log::info($title, $logInfo, 'cmd');
    }
}